import { Button, Calendar, Badge, Form, Space, Tag, message } from 'antd';
import type { BadgeProps } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { Dayjs } from 'dayjs';
import type { CalendarMode } from 'antd/es/calendar/generateCalendar';
import { sortTran, filterTran } from '@/utils/requestUtil';
import {
  getFactoryCalendarByPage,
  addFactoryCalendar,
  updateFactoryCalendar,
  delFactoryCalendar,
  exportFactoryCalendar,
} from '@/services/system/factoryCalendar';
import { ProList } from '@ant-design/pro-list';
import dayjs from 'dayjs';
import {
  ModalForm,
  ProFormText,
  ProFormTextArea,
  ProFormSwitch,
  ProCard,
  ProFormSelect,
} from '@ant-design/pro-components';
import React, { useEffect, useRef, useState } from 'react';
import { useLocation, useModel } from 'umi';

import {
  getFactoryCalendarItemByPage,
  addFactoryCalendarItem,
  updateFactoryCalendarItem,
  delFactoryCalendarItem,
  exportFactoryCalendarItem,
  getRangeItems,
} from '@/services/system/factoryCalendarItem';

const getListData = (value: Dayjs) => {
  let listData;
  switch (value.date()) {
    case 8:
      listData = [
        { type: 'warning', content: 'This is warning event.' },
        { type: 'success', content: 'This is usual event.' },
      ];
      break;
    case 10:
      listData = [
        { type: 'warning', content: 'This is warning event.' },
        { type: 'success', content: 'This is usual event.' },
        { type: 'error', content: 'This is error event.' },
      ];
      break;
    case 15:
      listData = [
        { type: 'warning', content: 'This is warning event' },
        { type: 'success', content: 'This is very long usual event。。....' },
        { type: 'error', content: 'This is error event 1.' },
        { type: 'error', content: 'This is error event 2.' },
        { type: 'error', content: 'This is error event 3.' },
        { type: 'error', content: 'This is error event 4.' },
      ];
      break;
    default:
  }
  return listData || [];
};

const MyCalendar: React.FC = () => {
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('新建'); //
  const [form] = Form.useForm();
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [selectDate, setSelectDate] = useState(null);
  const [initDates, setInitDates] = useState([]);
  const [rowData, setRowData] = useState({});
  const location = useLocation();

  const [modalVisit2, setModalVisit2] = useState(false); // 新建和编辑提示框
  const [formTitle2, setFormTitle2] = useState('新建'); //

  const [form2] = Form.useForm();
  const actionRef = useRef<ActionType>();
  const [messageApi, contextHolder] = message.useMessage();
  const [createOrUpdate2, setCreateOrUpdate2] = useState(false);

  useEffect(() => {
    // Using an IIFE
    (async () => {
      // 相当于新建
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getRangeItems({
          factoryCalendarId: location.query.id,
          date: dayjs().format('YYYY-MM-DD'),
        });
        setInitDates(result.data);
      }
    })();
  }, []);
  const handleSubmit = async (values) => {
    // if (formTitle == '新建') {
    // } else {
    // }
    const result = await addFactoryCalendarItem({
      ...values,
      factoryCalendarId: rowData.id,
      date: selectDate,
    });
    setInitDates(result.data);
    setModalVisit(false);
  };
  const handleSubmit2 = async (values) => {
    debugger;
    if (formTitle2 == '新建') {
      const result = await addFactoryCalendar(values);
    } else {
      await updateFactoryCalendar(values);
    }
    actionRef?.current.reload();
    // setConfirmLoading(false);

    setModalVisit2(false);
    // if (formTitle2 == '新建') {
    //   const result = await addFactoryCalendar(values);
    //   if (result != null) {
    //     message.success('添加成功');
    //   }
    // } else {
    //   await updateFactoryCalendar(values);
    // }
    // actionRef?.current.reload();
    // // setConfirmLoading(false);
    // setModalVisit2(false);
  };
  const dateCellRender = (value: Dayjs) => {
    const tempDate = value.format('YYYY-MM-DD');
    const queryItem = initDates.filter((item) => item.date === tempDate);
    console.log(queryItem, '---queryItem---');
    if (queryItem.length > 0) {
      return (
        <ul className="events">
          <a
            key="editKey"
            onClick={(e) => {
              debugger;
              e.stopPropagation();
              console.log(rowData?.id, '---rowData?.id----');
              if (rowData != null && rowData != undefined) {
                setModalVisit(true);
                setSelectDate(value.format('YYYY-MM-DD'));
                setFormTitle('添加备注信息');
                // setFormTitle('编辑');
              } else {
                message.error('请先选择日历');
              }
            }}
          >
            设置
          </a>
          <li style={{ color: 'red' }}>{queryItem[0].calenderMemo}</li>
          <li>休息</li>
        </ul>
      );
    } else {
      return (
        <ul className="events">
          <a
            key="editKey"
            onClick={() => {
              if (rowData.id != null && rowData.id != undefined) {
                setModalVisit(true);
                setSelectDate(value.format('YYYY-MM-DD'));
                setFormTitle('添加备注信息');
                setFormTitle('编辑');
              } else {
                message.error('请先选择日历');
              }
            }}
          >
            设置
          </a>
        </ul>
      );
    }
  };

  const onPanelChange = async (value: Dayjs, mode: CalendarMode) => {
    const result = await getRangeItems({
      factoryCalendarId: rowData.id,
      date: value.format('YYYY-MM-DD'),
    });
    setInitDates(result.data);

    // console.log('--- onPanelChange={onPanelChange}----');
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProCard split="vertical">
        <ProCard title="" colSpan="40%">
          <ProList
            toolBarRender={() => {
              return [
                <Button
                  key="3"
                  type="primary"
                  onClick={() => {
                    setModalVisit2(true);
                  }}
                >
                  新建
                </Button>,
              ];
            }}
            actionRef={actionRef} //用于触发刷新操作等，看api
            // search={{
            //   filterType: 'light',
            // }}
            rowKey="name"
            headerTitle="日历管理"
            pagination={{
              pageSize: 5,
            }}
            request={async (params = {}, sort, filter) => {
              const sorters = sortTran(sort);
              const filters = filterTran(params);
              const result = await getFactoryCalendarByPage({
                ...params,
                sorters: sorters,
                filters: filters,
              });
              return {
                data: result.data.content,
                total: result.data.totalElements,
                success: result.success,
              };
            }}
            metas={{
              title: {
                dataIndex: 'calendarName',
                title: '名称',
              },
              description: {
                dataIndex: 'calendarCode',
                title: '编号',
              },
              subTitle: {
                dataIndex: 'type',
                render: (_, row) => {
                  return (
                    <Space size={0}>
                      {row.type ? (
                        <Tag color="blue">{'标准日历'}</Tag>
                      ) : (
                        <Tag color="green">{'自定义日历'}</Tag>
                      )}
                    </Space>
                  );
                },
                search: false,
              },
              actions: {
                render: (text, row) => [
                  <a
                    target="_blank"
                    rel="noopener noreferrer"
                    key="link"
                    onClick={async () => {
                      await delFactoryCalendar({ id: row.id });
                      actionRef.current.reload();
                    }}
                  >
                    删除
                  </a>,
                  <a
                    target="_blank"
                    rel="noopener noreferrer"
                    key="warning"
                    onClick={() => {
                      setModalVisit2(true);
                      setCreateOrUpdate2(true);
                      setFormTitle2('编辑');
                      form2.setFieldsValue({
                        calendarCode: row.calendarCode,
                        calendarName: row.calendarName,
                        type: row.type,
                        id: row.id,
                      });
                    }}
                  >
                    编辑
                  </a>,
                  <a
                    target="_blank"
                    rel="noopener noreferrer"
                    key="view"
                    onClick={async (e) => {
                      // setRowData(record);
                      // actionRef.current.reload();
                      // setDeleteVisit(true);
                      e.stopPropagation(); //阻止点击事件冒泡
                      setRowData(row);
                      const result = await getRangeItems({
                        factoryCalendarId: row.id,
                        date: dayjs().format('YYYY-MM-DD'),
                      });
                      setInitDates(result.data);
                      // actionRef.current.reload();
                    }}
                  >
                    查看
                  </a>,
                ],
                search: false,
              },
            }}
          />
        </ProCard>
        <ProCard title={'<<' + rowData?.calendarName + '>>日历的详细设计'} headerBordered>
          <Calendar
            dateCellRender={dateCellRender}
            onChange={(date: Dayjs) => {
              // setModalVisit(true);
              // setFormTitle('添加备注信息');
              form.resetFields();
              console.log(date.date(), date.month(), date.format('YYYY-MM-DD'));
            }}
            onPanelChange={onPanelChange}
          />
        </ProCard>
      </ProCard>

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        onFinish={handleSubmit}
        form={form}
        modalProps={{
          destroyOnClose: false,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
      >
        <ProFormSwitch
          initialValue={false}
          name="dayOff"
          label="是否休息"
          placeholder="请输入名称"
          disabled={createOrUpdate}
          rules={[{ required: true, message: 'Please input your calendarCode!' }]}
        />
        <ProFormTextArea
          name="calenderMemo"
          label="备注信息"
          placeholder="请输入名称"
          fieldProps={{ width: '100%', showCount: true, maxLength: 20, rows: 1 }}
          disabled={createOrUpdate}
          rules={[{ required: true, message: 'Please input your calenderName!' }]}
        />
      </ModalForm>

      <ModalForm
        visible={modalVisit2}
        title={formTitle2}
        onFinish={handleSubmit2}
        form={form2}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit2(false);
          },
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="calendarCode"
          label="日历编号"
          placeholder="请输入名称"
          disabled={createOrUpdate2}
          rules={[{ required: true, message: 'Please input your calendarCode!' }]}
        />
        <ProFormText
          name="calendarName"
          label="日历名称"
          placeholder="请输入名称"
          // disabled={createOrUpdate2}
          rules={[{ required: true, message: 'Please input your calenderName!' }]}
        />

        <ProFormTextArea
          name="calenderMemo"
          label="备注信息"
          placeholder="请输入名称"
          fieldProps={{ width: '100%', showCount: true, maxLength: 20, rows: 1 }}
          // disabled={createOrUpdate2}
          rules={[{ required: true, message: 'Please input your calenderName!' }]}
        />
        {/* <ProFormText
          name="type"
          label="类型"
          placeholder="请输入名称"
          disabled={createOrUpdate}
          rules={[{ required: true, message: 'Please input your type!' }]}
        /> */}
        <ProFormSelect
          name="type"
          colProps={{ md: 12, xl: 8 }}
          label="类型"
          options={[
            { label: '标准日历', value: 1 },
            { label: '自定义日历', value: 0 },
          ]}
          disabled={createOrUpdate2}
        />
      </ModalForm>
    </PageHeaderWrapper>
  );
};

export default MyCalendar;
